package pub.elephants.socket.netty.client;

import org.apache.commons.pool2.impl.GenericObjectPool;
import pub.elephants.net.body.ElephantsCallBack;
import pub.elephants.net.body.ElephantsRequest;
import pub.elephants.net.body.ElephantsResponse;
import pub.elephants.net.client.ElephantsClient;

public class NettyClient extends ElephantsClient {
    /**
     * @param request
     * @return
     * @throws Exception
     */
    public ElephantsResponse send(ElephantsRequest request) throws Exception {
        GenericObjectPool<NettyClientPoolProxy> clientPool = NettyClientPool.getPool(serverAddress, request.getClassName(), serializer);
        NettyClientPoolProxy clientPoolProxy = null;
        try {
            ElephantsCallBack elephantsBack = new ElephantsCallBack(request);
            ElephantsCallBack.requestPool.put(request.getRequestId(), elephantsBack);
            clientPoolProxy = clientPool.borrowObject();
            clientPoolProxy.send(request);
            return elephantsBack.getElephantsResponse(timeoutMillis);
        } catch (Exception e) {
            throw e;
        } finally {
            ElephantsCallBack.requestPool.remove(request.getRequestId());
            clientPool.returnObject(clientPoolProxy);
        }
    }
}
